import 'package:flutter/material.dart';

class CustomSlider extends StatefulWidget {
	@override createState() => _CustomSliderState();
	final List<Widget> children;
	final double childWidth;
	final double percent;
	final PageController controller;
	void Function(double page) onPageChange;

	CustomSlider({@required this.children, @required this.childWidth, this.percent = 0.8, this.onPageChange, this.controller,}) {
		this.onPageChange ??= (page){};
	}
}

class _CustomSliderState extends State<CustomSlider>{
	PageController _controller;

	@override
	initState() {
		_controller = widget.controller ?? PageController();
		super.initState();
	}

	@override
	dispose() {
		super.dispose();
	}

	@override build(BuildContext context) {

		var page = PageView(
			controller: _controller,
			children: widget.children.map((_) => Container()).toList(),
		);

		var childs = <Widget>[];
		for (var index = 0; index < widget.children.length; index++) {
			childs.add(LayoutBuilder(
				builder: (context, constraint) => AnimatedBuilder(
					animation: _controller,
					child: widget.children[widget.children.length - 1 - index],
					builder: (context, child){
						var page = _controller.positions.isEmpty ? 0.0 : _controller.page ?? 0.0;
						var buildingWidget = widget.children[index];

						var scale = 0.0;

						if (page > index) scale = 1.0 - (page - index);
						if (page < index) scale = 1.0 - (index - page);
						if (page == index) scale = 1.0;
						if (scale < 0) scale = 0.0;
						if (scale >= 1) scale = 1.0;

						scale = scale / (1 / (1 - widget.percent));
						scale += widget.percent;

						var xPoint = ((widget.childWidth) * index) - (page * (widget.childWidth) );
//						xPoint += constraint.maxWidth / 2 - widget.childWidth / 2;

						buildingWidget = Transform(
							transform: Matrix4.translationValues(xPoint, 0.0, 0.0)..scale(scale, scale),
							child: child,
							alignment: Alignment.center,
						);

						widget.onPageChange(page);

						return buildingWidget;
					},
				),
			));
		}

		return Stack(
			children: <Widget>[
				...childs,
				page,
			],
		);
	}
}
